<template>
  <el-card header="老师信息" style="margin-top:10px">
    <el-button v-if="canEdit" type="primary" size="medium" @click="addCol">
      新增
    </el-button>

    <el-form ref="authorForm" :model="authorForm" :rules="rules">
      <el-table
        :data="authorForm.authorDataList"
        border
        fit
        highlight-current-row
        :header-cell-style="{ background: '#f5f7fa' }"
        style="width: 100%;margin-top:10px;"
      >
        <el-table-column label="署名顺序" align="center" width="80">
          <template slot-scope="scope">
            <el-form-item
              v-if="canEdit"
              :prop="'authorDataList.' + scope.$index + '.sign_order'"
              :rules="rules.sign_order"
            >
              <el-input v-model.number="scope.row.sign_order" size="small" />
            </el-form-item>
            <span v-else> {{ scope.row.sign_order }} </span>
          </template>
        </el-table-column>

        <el-table-column label="作者类型" align="center">
          <template slot-scope="scope">
            <el-form-item
              v-if="canEdit"
              :prop="'authorDataList.' + scope.$index + '.author_type'"
            >
              <el-select
                
                v-model="scope.row.author_type"
                size="small"
                style="width:100%"
                @change="authorTypeChange(scope.row, scope.$index)"
              >
                <el-option
                  v-for="item in authorTypeList"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
            <span v-else> {{ scope.row.author_type }} </span>
          </template>
        </el-table-column>

        <el-table-column label="作者姓名" align="center" width="150">
          <template slot-scope="scope">
            <el-form-item
              v-if="canEdit"
              :prop="'authorDataList.' + scope.$index + '.name'"
              :rules="rules.name"
            >
              <el-select
                placeholder="请选择"
                v-model="row_data[scope.$index]"
                v-if="scope.row.author_type == '本校学生'"
                value-key="id"
                size="small"
                :filter-method="
                  e => {
                    searchAccount(e, scope.row);
                  }
                "
                filterable
                @change="nameChange($event, scope.row)"
              >
                <el-option
                  v-for="item in studentList"
                  :key="item.id"
                  :label="item.realname"
                  :value="item"
                >
                </el-option>
              </el-select>

              <el-select
                placeholder="请选择"
                v-model="row_data[scope.$index]"
                v-if="scope.row.author_type == '本校老师'"
                value-key="id"
                size="small"
                :filter-method="
                  e => {
                    searchAccount(e, scope.row);
                  }
                "
                filterable
                @change="nameChange($event, scope.row)"
              >
                <el-option
                  v-for="item in teacherList"
                  :key="item.id"
                  :label="item.realname"
                  :value="item"
                >
                </el-option>
              </el-select>

              <el-input
                v-if="scope.row.author_type == '外校老师'"
                v-model="scope.row.name"
                size="small"
              />
            </el-form-item>
            <span v-else> {{ scope.row.realname||scope.row.name }} </span>
          </template>
        </el-table-column>

        <el-table-column label="性别" align="center" width="80">
          <template slot-scope="scope">
            <el-form-item
              v-if="canEdit"
              :prop="'authorDataList.' + scope.$index + '.sex'"
            >
              <el-select v-model="scope.row.sex" size="small">
                <el-option
                  v-for="item in sexList"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
            <span v-else> {{ scope.row.sex }} </span>
          </template>
        </el-table-column>

        <el-table-column label="学历" align="center">
          <template slot-scope="scope">
            <el-form-item
              v-if="canEdit"
              :prop="'authorDataList.' + scope.$index + '.education'"
              :rules="rules.education"
            >
              <el-select v-model="scope.row.education" size="small">
                <el-option
                  v-for="item in educationList"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
            <span v-else> {{ scope.row.education }} </span>
          </template>
        </el-table-column>

        <el-table-column label="职称" align="center">
          <template slot-scope="scope">
            <el-form-item
              v-if="canEdit"
              :prop="'authorDataList.' + scope.$index + '.job_title'"
              :rules="rules.job_title"
            >
              <el-select v-model="scope.row.job_title" size="small">
                <el-option
                  v-for="item in jobTitleList"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
            <span v-else> {{ scope.row.job_title }} </span>
          </template>
        </el-table-column>

        <el-table-column label="所属学院" align="center" width="200">
          <template slot-scope="scope">
            <el-form-item
              v-if="canEdit"
              :prop="'authorDataList.' + scope.$index + '.faculty_code'"
            >
              <!-- <el-input v-model="scope.row.faculty" size="small"></el-input> -->
              <el-select
                disabled
                v-model="scope.row.faculty_code"
                size="small"
                clearable
                placeholder="请选择"
                filterable
              >
                <el-option
                  v-for="item in facultyList"
                  :key="item.id"
                  :label="item.faculty_title"
                  :value="item.faculty_code"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <span v-else> {{ scope.row.faculty_title }} </span>
          </template>
        </el-table-column>

        <el-table-column label="贡献率" align="center" width="130">
          <template slot-scope="scope">
            <el-form-item
              v-if="canEdit"
              :prop="'authorDataList.' + scope.$index + '.contribution_rate'"
              :rules="rules.contribution_rate"
            >
              <el-input v-model="scope.row.contribution_rate" size="small" />
            </el-form-item>
            <span v-else> {{ scope.row.contribution_rate }} </span>
          </template>
        </el-table-column>

        <el-table-column v-if="canEdit" label="操作" align="center">
          <template slot-scope="{ row, $index }">
            <el-button
              type="danger"
              size="mini"
              plain
              icon="el-icon-delete"
              @click.native="deleteCol(row, $index)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>

      </el-table>
    </el-form>
  </el-card>
</template>

<script>
import { AuthorType, Education, JobTitle } from "@/utils/variable";
import { searchAccount, getFaculty } from "@/api/account";

const defaultAuthor = {
  sign_order: 1,
  author_type: "本校老师",
  sex: "男",
  name: null
};

export default {
  props: {
    data: {
      type: Array,
      default: () => []
    },
    canEdit: {
      type: Boolean,
      default: true
    }
  },
  data() {
    
    let authorType=JSON.parse(JSON.stringify(AuthorType))
    authorType.splice(1, 1);
    authorType.splice(1, 1);
    var validateSignOrder = (rule, value, callback) => {
      var val = Number(value);
      if (isNaN(val) || !Number.isInteger(val) || val < 1) {
        callback(new Error("必须为正整数"));
      } else {
        callback();
      }
    };
    var validateContribucationRate = (rule, value, callback) => {
      var val = Number(value);
      if (isNaN(val) || val < 0 || val > 100) {
        callback(new Error("应为0-100的数字"));
      } else {
        callback();
      }
    };
    return {
      sexList: ["男", "女"],
      educationList: Education,
      authorTypeList: authorType,
      jobTitleList: JobTitle,
      facultyList: [],
      studentList: [],
      teacherList: [],
      facultyList: [],
      row_data: [],
      authorForm: {
        authorDataList: [
        ]
      },
      rules: {
        sign_order: [
          { required: true, message: "必须填写", trigger: "blur" },
          { validator: validateSignOrder, trigger: "blur" }
        ],
        contribution_rate: [
          { required: true, message: "必须填写", trigger: "blur" },
          { validator: validateContribucationRate, trigger: "blur" }
        ],
        name: [{ required: true, message: "必须填写", trigger: "blur" }],
        job_num: [{ required: true, message: "必须填写", trigger: "blur" }],
        education: [{ required: true, message: "必选", trigger: "blur" }],
        job_title: [{ required: true, message: "必选", trigger: "blur" }],
        sex: [{ required: true, message: "必须填写", trigger: "blur" }]
      }
    };
  },
  watch: {
    data(newVal, oldVal) {
      this.row_data = [];
      this.studentList = [];
      this.teacherList = [];
      this.authorForm.authorDataList = JSON.parse(JSON.stringify(newVal));
      for (let i = 0; i < newVal.length; i++) {
        this.row_data.push({ id: newVal[i].id });
        newVal[i].author_type == "本校学生" && newVal[i].id
          ? this.studentList.push(newVal[i])
          : null;

        newVal[i].author_type == "本校老师" && newVal[i].id
          ? this.teacherList.push(newVal[i])
          : null;
      }
    }
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      getFaculty().then(response => {
        this.facultyList = response;
      });
    },
    // 新增一行
    addCol() {
      // 此处必须进行深拷贝
      const newColData = JSON.parse(JSON.stringify(defaultAuthor));
      this.authorForm.authorDataList.push(newColData);
    },
    // 删除所选行
    deleteCol(row, index) {
      this.authorForm.authorDataList.splice(index, 1);
      this.row_data.splice(index, 1);
    },
    // 提交表单
    commitAuthor() {
      this.$refs["authorForm"].validate(valid => {
          this.$emit("getAuthorData", this.authorForm,valid);
      });
    },

    resetForm() {
      this.$refs["authorForm"].resetFields();
      this.row_data = [];
    },

    nameChange(i, row) {
      row.name = i.id;
      row.job_num = i.username;
      row.faculty_code = i.faculty_code;
      row = JSON.parse(JSON.stringify(row));
    },

    searchAccount(e, row) {
      if (!e) return;
      if (row.author_type == "本校学生") {
        searchAccount({ realname: e, type: "学生" }).then(response => {
          this.studentList = response;
        });
      } else if (row.author_type == "本校老师") {
        searchAccount({ realname: e, type: "教师" }).then(response => {
          this.teacherList = response;
        });
      }
    },

    authorTypeChange(row, index) {
      row.name = null;
      row.id = null;
      this.row_data[index] = null;
    }
  }
};
</script>
